package com.hbx.educenter.controller;

import com.google.gson.Gson;
import com.hbx.commonutils.JwtUtils;
import com.hbx.educenter.entity.UcenterMember;
import com.hbx.educenter.service.UcenterMemberService;
import com.hbx.educenter.utils.ConstantPropertiesUtil;
import com.hbx.educenter.utils.HttpClientUtils;
import com.hbx.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author hbx
 * @Date 2023/10/16 18:51
 */
@Api(tags = {"微信登陆管理"})
@Controller //只是请求地址，不需要返回数据，所以不能用@RestController注解，不然会返回地址字符串
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 获取扫描人信息，添加数据
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code,String state){
       try{
           //1.获取code值，临时票据，类似于验证码
           //2.拿着code 请求微信固定的地址，得到两个值 access_token 和 openid
           String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                   "?appid=%s" +
                   "&secret=%s" +
                   "&code=%s" +
                   "&grant_type=authorization_code";

           String accessTokenUrl = String.format(baseAccessTokenUrl,
                   ConstantPropertiesUtil.WX_OPEN_APP_ID,
                   ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                   code);
           //请求这个拼接好的地址，得到返回的两个值 access_token 和 openid
           //使用httpclient发送请求，得到返回结果
           String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

           //从accessTokenInfo字符串获取出来两个值 access_token 和 openid
           //把accessTokenInfo字符串转换为map集合，根据map的key获取value值
           //使用json转换工具 Gson
           Gson gson = new Gson();
           HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
           String accessToken = (String) mapAccessToken.get("access_token");
           String openId = (String) mapAccessToken.get("openid");

           //把扫描人的信息添加到数据库中
           //判断数据库中是否存在该信息
           UcenterMember member = ucenterMemberService.getOpenIdMember(openId);
           if(member == null){

               //3.拿着得到的 access_token 和 openid。再去请求微信提供的固定地址，获取扫描人的信息
               //访问微信的资源服务器，获取用户信息
               String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                       "?access_token=%s" +
                       "&openid=%s";
               String userInfoUrl = String.format(
                       baseUserInfoUrl,
                       accessToken,
                       openId);
               //发送请求
               String userInfo = HttpClientUtils.get(userInfoUrl);
               //获取返回userInfo扫描人信息
               HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
               String nickName = (String) userInfoMap.get("nickname");//用户昵称
               String headImgUrl = (String) userInfoMap.get("headimgurl");//用户头像

               member = new UcenterMember();
               member.setOpenid(openId);
               member.setNickname(nickName);
               member.setAvatar(headImgUrl);
               ucenterMemberService.save(member);
           }

           //存入cookie
           //CookieUtils.setCookie(request, response, "guli_jwt_token", token);

           //因为端口号不同存在跨域问题，cookie不能跨域，所以这里使用url重写

           //使用jwt根据member对象生成token字符串
           String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
           //最后返回首页面，通过路径传递token
           return "redirect://localhost:3000?token="+jwtToken;
       }catch (Exception e){
           throw new GuliException(20001,"登陆失败");
       }
    }

    /**
     * 微信扫描生成二维码
     * @return
     */
    @GetMapping("/login")
    public String login(){
        // 微信开放平台授权baseUrl %s相当于占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";


        //对redirect_url进行urlEncode编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置%s里面的值
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "hbx"
        );
        //重定向到请求微信地址里面
        return "redirect:"+url;
    }
}
